//
//  SendMsgViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/10/31.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "SendMsgViewController.h"
#import "SendMsgTableViewCell.h"
#import "SendMsgTitleTableViewCell.h"
#import "SendMsgContentTableViewCell.h"
#import "MsgFootView.h"
#import "SendMsgModel.h"
#import "MsgObjTableViewCell.h"
#import "ChooseView.h"
#import "RegisterShopModel.h"
#import "ChooseMoreViewController.h"
@interface SendMsgViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>

@property(nonatomic,strong)TB_TableView*homeTableView;

@property(nonatomic,strong)SendMsgModel *sendModel;

@property(nonatomic,strong)NSMutableArray *MsgobjcArr;

@end

@implementation SendMsgViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.sendModel=[SendMsgModel new];
    
    self.sendModel.isAll=YES;//初始化为全部
    
    if ([self getUserType]==1) {
        
        NSDictionary *sender=@{@"id":[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]],@"name":[LoginStatuesModel shopName]};
        
        self.sendModel.sender=[HelpWay dictionaryToJSON:sender];
        
    }else{
        
        NSDictionary *sender=@{@"id":[NSString stringWithFormat:@"%ld",[LoginStatuesModel getStaffId]],@"name":[LoginStatuesModel getStaffName]};
        
        self.sendModel.sender=[HelpWay dictionaryToJSON:sender];
        
    }
    
    self.title=@"写消息";
    
    [self.view addSubview:self.homeTableView];
    
     [self loadDatasIsFirst:YES];//第一次请求，如果请求成功，不作第二次请求
    // Do any additional setup after loading the view.
}


-(NSMutableArray*)MsgobjcArr
{
    if (!_MsgobjcArr) {
        
        _MsgobjcArr=[NSMutableArray array];
        
    }
    
    return _MsgobjcArr;
}

-(void)loadDatasIsFirst:(BOOL)isfirst
{
    [self showLoadingAnimation];
    
    NSString *logintypeStr=[NSString stringWithFormat:@"%ld",[self getUserType]];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/messageSendType.json" andrequestTime:5 andParams:@{@"loginType":logintypeStr} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            //请求成功
            NSArray *ReqArr=responseObject[@"data"];
            
            for (NSDictionary *obdic in ReqArr) {
                
                RSItems *items=[RSItems new];
                
                items.name=obdic[@"name"];
                
                items.value=obdic[@"id"];
                
                [self.MsgobjcArr addObject:items];
                
            }
            
            if (!isfirst) {
                //如果是第二次，需弹出选择框
                
                [self ChooseObj];
            }

        }
        
    }];
    
    
    
}

-(TB_TableView*)homeTableView
{
    if (!_homeTableView) {
        
        _homeTableView=[[TB_TableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
        
        _homeTableView.delegate=self;
        
        _homeTableView.dataSource=self;
        
        _homeTableView.tableFooterView=[[UIView alloc]init];
     
        [_homeTableView registerNib:[UINib nibWithNibName:@"MsgObjTableViewCell" bundle:nil] forCellReuseIdentifier:@"ObjcCell"];
        
        [_homeTableView registerNib:[UINib nibWithNibName:@"SendMsgTableViewCell" bundle:nil] forCellReuseIdentifier:@"Receivecell"];
        
           [_homeTableView registerNib:[UINib nibWithNibName:@"SendMsgTitleTableViewCell" bundle:nil] forCellReuseIdentifier:@"Titcell"];
        
           [_homeTableView registerNib:[UINib nibWithNibName:@"SendMsgContentTableViewCell" bundle:nil] forCellReuseIdentifier:@"Concell"];
        
        [_homeTableView registerClass:[MsgFootView class] forHeaderFooterViewReuseIdentifier:@"Foot"];
        
        
    }
    return _homeTableView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 4;
    
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row==0) {
        
        MsgObjTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"ObjcCell" forIndexPath:indexPath];
        
        cell.PostObjLabel.text=self.sendModel.mapName;
        
        return cell;
        
    }else if (indexPath.row==1) {
        
        SendMsgTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Receivecell" forIndexPath:indexPath];
        
         if (self.sendModel.mapType.length==0||[self.sendModel.mapName isEqualToString:@"平台"]) {
             
             cell.isHiden=YES;
             
         }else{
             
             cell.isHiden=NO;
             
         }
    
        if (self.sendModel.isAll) {
            
            if (self.sendModel.mapName.length!=0) {
                
                 cell.NumLable.text=[NSString stringWithFormat:@"默认发送全部%@",self.sendModel.mapName];
            }else{
                
                cell.NumLable.text=@"";
                
            }
  
        }else{
            
            cell.NumLable.text=[NSString stringWithFormat:@"已经选择了%ld位%@",self.sendModel.count,self.sendModel.mapName];
    
        }
       
 
        cell.block=^(NSInteger type)
        {

            [self ChoosePostMan];
            
            
        };
        
        return cell;
        
        
    }else if (indexPath.row==2)
    {
        
        SendMsgTitleTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Titcell" forIndexPath:indexPath];
        
        [cell.MsgTitleLabel addTarget:self action:@selector(textEditingChanged:) forControlEvents:UIControlEventEditingChanged];
        
        return cell;
        
    }else{
        
        
        SendMsgContentTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Concell" forIndexPath:indexPath];
        
        cell.msgTextView.delegate=self;
        
        return cell;
        
    }
    
}


-(void)ChoosePostMan
{
    //除了平台外，不需要列表
    
    ChooseMoreViewController *choose=[ChooseMoreViewController new];
    
    JobListModel *ReqModel=[JobListModel new];
    
    choose.title=[NSString stringWithFormat:@"选择发送%@",self.sendModel.mapName];
    
    if ([self.sendModel.mapName isEqualToString:@"商户"]) {
        
        choose.DataReqStr=@"/index.php/FoodCheckApi/shopList.json";
        
        if ([self getUserType]==3) {
            
            ReqModel.marketId=[LoginStatuesModel getStaffId];
            
        }
        
        choose.Reqmodel=ReqModel;
        
        choose.listType=0;
    
    }else if ([self.sendModel.mapName isEqualToString:@"检查员"])
    {
        
        choose.DataReqStr=@"/index.php/FoodCheckApi/checkerList.json";
        
        ReqModel.type=@"2";
        
        choose.Reqmodel=ReqModel;
        
        choose.listType=1;
        
    }else if ([self.sendModel.mapName isEqualToString:@"开办方"])
    {
        choose.DataReqStr=@"/index.php/FoodCheckApi/marketList.json";
        
        choose.Reqmodel=ReqModel;
        
        choose.listType=2;
        
        
    }else if ([self.sendModel.mapName isEqualToString:@"管理员"])
    {
        
        choose.DataReqStr=@"/index.php/FoodCheckApi/checkerList.json";
        
        ReqModel.type=@"1";
        
        choose.Reqmodel=ReqModel;
        
        choose.listType=3;
        
    }
    
    choose.block=^(NSString *receiver,NSInteger count)
    {
        
        self.sendModel.isAll=NO;
        
        self.sendModel.receiver=receiver;
        
        self.sendModel.count=count;
        
        [self.homeTableView reloadData];
        
    };
    
    
    [self.navigationController pushViewController:choose animated:YES];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0||indexPath.row==2) {
        
        return 44;
    }
    
    if (indexPath.row==1) {
        
        if (self.sendModel.mapType.length==0||[self.sendModel.mapName isEqualToString:@"平台"]) {
  
            return 0;
     
        }else{
            
            return 44;
            
        }
    }
    
    return 150;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 90;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}


-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    MsgFootView *foot=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"Foot"];
    
    [foot.MainBtn addTarget:self action:@selector(SendMsg) forControlEvents:UIControlEventTouchUpInside];
    
    return foot;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        
        if (self.MsgobjcArr.count!=0) {
            
             [self ChooseObj];
            
        }else{
            
            [self loadDatasIsFirst:NO];
            
        }
  
    }else if (indexPath.row==1)
    {
     
        if (![self.sendModel.mapName isEqualToString:@"平台"]) {
            
             [self ChoosePostMan];
        }
        
        
    }

}


-(void)ChooseObj
{
    ChooseView *chooseView=[[ChooseView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kDevice_Is_iPhoneX?SCREEN_HEIGHT-64-IPhoneXTableHeight:SCREEN_HEIGHT-64) andDataArr:self.MsgobjcArr andBlock:^(NSString *value, NSInteger index) {
       
        self.sendModel.isAll=YES;
        
        self.sendModel.count=0;
        
        self.sendModel.mapType=value;
        
        RSItems *items=self.MsgobjcArr[index];
        
        self.sendModel.mapName=items.name;
        
        NSMutableArray *receiveArr=[NSMutableArray array];
        
        if ([items.name isEqualToString:@"平台"]) {
            
            NSDictionary *Receivedic=@{@"id":@"center",@"name":@"平台"};
            
            [receiveArr addObject:Receivedic];
            
        }else{
            
            //默认为全部
            
            NSDictionary *Receivedic=@{@"id":@"all",@"name":@"所有"};
            
            [receiveArr addObject:Receivedic];
        }
        
        
        
        self.sendModel.receiver=[HelpWay arrToJSON:receiveArr];

        [self.homeTableView updateWithBlock:^(UITableView * _Nonnull tableView) {

            [tableView reloadData];
            
        }];
        
    }];
    
    [chooseView PopWithView:self.view];
    
}



-(void)textEditingChanged:(UITextField*)textfile
{
    self.sendModel.title=textfile.text;
}

- (void)textViewDidChange:(UITextView *)textView
{
    
    self.sendModel.content=textView.text;
    
}


-(void)SendMsg
{
    
    if (self.sendModel.mapType.length==0) {
        
        [MBProgressHUD showWarnMessage:@"发送对象不能为空"];
        
        return;
    }
    
    if (self.sendModel.title.length==0) {
        
        [MBProgressHUD showWarnMessage:@"发送标题不能为空"];
    
        return;
    }
    
    if (self.sendModel.content.length==0) {
        
        [MBProgressHUD showWarnMessage:@"发送内容不能为空"];
        
        return;
    }
    
    
    [self showLoadingAnimation];
    
   NSDictionary*dict =[self.sendModel mj_keyValuesWithIgnoredKeys:@[@"mapName",@"isAll",@"count"]];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/messageSend.json" andrequestTime:5 andParams:dict andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
 
        if (responseStatus==1) {
            //请求成功
     
            [MBProgressHUD showSuccessMessage:@"发送成功"];
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }else if (responseStatus==0||responseStatus==2)
        {
           
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
